package com.zhouheng.common.base;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class Context {
    private static ThreadLocal<Map<String, Object>> holder = new ThreadLocal<>();

    private Context() {
    }

    public static void clearAll() {
        dataMap().clear();
    }

    public static <T> Optional<T> get(String key) {
        return (Optional<T>) Optional.ofNullable(dataMap().get(key));
    }

    public static void set(String key, Object value) {
        dataMap().put(key, value);
    }

    public static <T> Optional<T> del(String key) {
        return (Optional<T>) Optional.ofNullable(dataMap().remove(key));
    }

    private static Map<String, Object> dataMap() {
        return Optional.ofNullable(holder.get()).orElseGet(() -> {
            Map<String, Object> newMap = new HashMap<>();
            holder.set(newMap);
            return newMap;
        });
    }
}
